from datetime import datetime

from flask import current_app
from flask import g
from flask import request, jsonify
from ihome_blue import ihome_blue
from models import Area, House
from utils.commons import user_login_data
from utils.constants import HOUSE_DETAIL_COMMENT_DISPLAY_COUNTS
from utils.response_code import RET



@ihome_blue.route('/houses', methods=['GET'])
def get_houses_list():

    aid = request.args.get('aid', 0) # 区域ID
    if aid == '':
        aid = 0
    start_day = request.args.get('sd', '1970-01-01') # 开始时间
    if start_day == '':
        start_day = '1970-01-01'
    end_day = request.args.get('ed', '1970-01-01') # 结束时间
    if end_day == '':
        end_day = '1970-01-01'
    sort_key = request.args.get('sk', 'new') # 排序方式
    if sort_key == '':
        sort_key = 'new'
    page = request.args.get('p', 1) # 页号
    try:
        page = int(page)
    except Exception as e:
        page = 1
    live_time =datetime.strptime(start_day, "%Y-%m-%d").day - \
                datetime.strptime(end_day, "%Y-%m-%d").day

    if live_time < 0:
        return jsonify(errno=RET.DATAERR, errmsg='时间信息有误')

    paginate = None
    try:
        filters = []
        if aid != 0:
            filters.append(House.area_id == aid)
        if live_time > 0:
            filters.append(House.min_days <= live_time and (House.max_days == 0 or live_time <= House.max_days))
        if sort_key == 'new':
            sort_key = House.create_time.desc()
        if sort_key == 'booking':
            sort_key = House.order_count.desc()
        if sort_key == 'price-inc':
            sort_key = House.create_time.asc()
        if sort_key == 'price-des':
            sort_key = House.create_time.desc()
        paginate = House.query.filter(*filters).order_by(sort_key).paginate(page, HOUSE_DETAIL_COMMENT_DISPLAY_COUNTS, False)

    except Exception as e:
        current_app.logger.error(e)
        jsonify(errno=RET.DBERR, errmsg='获取新闻失败')

    totalPage = paginate.pages
    # currentPage = paginate.page
    items = paginate.items

    house_list = []
    for house in items:
        house_list.append(house.to_basic_dict())

    data = {
        'total_page' : totalPage,
        'houses' : house_list
    }

    return jsonify(errno=RET.OK, errmsg='OK', data=data)







# 城区列表
# 请求路径：/api/v1.0/areas
# 请求方式：GET
# 请求参数：无
# 返回响应
@ihome_blue.route('/areas')
@user_login_data
def areas():
    # 查询所有城区
    try:
        area_info = Area.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="城区信息获取失败")

    #区域对象列表转成字典列表
    area_list = []
    for area in area_info:
        area_list.append(area.to_dict())


    return jsonify(errno=RET.OK, errmsg="获取成功",data = area_list)


